package com.fg.cloud.factory.controller.factory;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fg.cloud.common.PageUtils;
import com.fg.cloud.common.StatusCode;
import com.fg.cloud.common.construction.Select;
import com.fg.cloud.common.construction.Tree;
import com.fg.cloud.common.quantity.ResultType;
import com.fg.cloud.common.validate.LongUtils;
import com.fg.cloud.framework.controller.BaseController;
import com.fg.cloud.manager.entry.agency.vo.AgencyVo;
import com.fg.cloud.manager.entry.factory.FactoryNewsEntity;
import com.fg.cloud.manager.entry.factory.vo.FactoryNewsVo;
import com.fg.cloud.manager.entry.factory.vo.FactoryUserVo;
import com.fg.cloud.manager.service.agency.AgencyAreaService;
import com.fg.cloud.manager.service.agency.AgencyLevelService;
import com.fg.cloud.manager.service.agency.AgencyService;
import com.fg.cloud.manager.service.factory.FactoryNewsService;

/**
 * @author liushengchao
 * @Description: 新闻公告业务 
 * @date 2017年6月14日下午2:30:15
 */
@Controller
@RequestMapping("/factoryNews")
public class FactoryNewsController extends BaseController{
	
	@Autowired
	private FactoryNewsService factoryNewsService;
	@Autowired
	private AgencyService agencyService;
	@Autowired
	private AgencyAreaService agencyAreaService;
	@Autowired
	private AgencyLevelService agencyLevelService;
	
	/**
	 * @Description: 新增新闻信息 
	 * @param req
	 * @param resp
	 * @param factoryNews 新闻信息实体
	 * @return void
	 * @author liushengchao
	 * @date 2017年6月14日下午2:53:20
	 * @throws 
	 */
	@RequestMapping(value="/insert",method={RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	public void insert(HttpServletRequest req, HttpServletResponse resp, FactoryNewsEntity factoryNews){
		try {
			//验证newsTitle和newsContent是否为空			
			if ( StringUtils.isEmpty(factoryNews.getNewsTitle()) ) {
				doResult(resp, false, StatusCode.SAVEERROR, null, "新闻标题不能为空");
				return ;
			}
			if (  StringUtils.isEmpty(factoryNews.getNewsContent()) ) {
				doResult(resp, false, StatusCode.SAVEERROR, null, "新闻内容不能为空");
				return ;
			}	
			//验证同一个厂商的newsTitle是否重复
			FactoryUserVo currentFactoryUser = getCurrentFactoryUser();
			factoryNews.setFacId(currentFactoryUser.getFacId());
			if ( factoryNewsService.selectBycondition(factoryNews) ) {
				doResult(resp, false, StatusCode.SAVEERROR, null, "新闻标题已存在");
				return ;
			}
			//验证reciverType参数合法
			if (factoryNews.getReciverType()!=null && factoryNews.getReciverType()!=0 && 
					factoryNews.getReciverType()!=1 && factoryNews.getReciverType()!=2 &&
					factoryNews.getReciverType()!=3) {
				doResult(resp, false, StatusCode.SAVEERROR, null, "请指定接收类型");
				return ;
			}
			FactoryUserVo facUser = getCurrentFactoryUser();
			boolean flag = factoryNewsService.insert(factoryNews, facUser);
			doResult(resp, flag, flag ? StatusCode.SAVESUCCESS : StatusCode.SAVEERROR, null, 
					flag ? ResultType.SAVE_SUCCESS : ResultType.SAVE_FAULT);
		} catch (Exception e) {
			e.printStackTrace();
			doResult(resp, false, StatusCode.SAVEERROR, null, e.getMessage());
		}
	}
	
	/**
	 * Description:获取当前厂商所有经销商列表
	 * @param req
	 * @param resp
	 * @author dingjiang
	 * @date 2017年9月19日下午1:44:14
	 */
	@RequestMapping(value="/findAge",method={RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	public void findAge(HttpServletRequest req , HttpServletResponse resp){
		try {
			AgencyVo agency = new AgencyVo();
			agency.setFacId(getCurrentFactoryUser().getFacId());
			List<Select> ages = agencyService.findBySelect(agency, "'aaa'");
			doResult(resp, true, StatusCode.FINDSUCCESS, ages, ResultType.FIND_SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
			doResult(resp, false, StatusCode.FINDERROR, null, e.getMessage());
		}
	}
	
	/**
	 * Description:获取当前厂商所有经销商区域列表
	 * @param req
	 * @param resp
	 * @author dingjiang
	 * @date 2017年9月19日下午2:36:40
	 */
	@RequestMapping(value="/findArea",method={RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	public void findArea(HttpServletRequest req , HttpServletResponse resp , Long facId){
		FactoryUserVo user = getCurrentFactoryUser();
		try {
			List<Tree> areaList = agencyAreaService.findListByNews(user.getFacId(), "'aaa'");
			doResult(resp, true, StatusCode.FINDSUCCESS, areaList, ResultType.FIND_SUCCESS);
		} catch (Exception e) {
			doResult(resp, false, StatusCode.FINDERROR, null, e.getMessage());
			e.printStackTrace();
		}		
	}
	
	/**
	 * Description:获取当前厂商所有经销商等级列表
	 * @param req
	 * @param resp
	 * @author dingjiang
	 * @date 2017年9月25日下午4:24:24
	 */
	@RequestMapping(value="/findLevel",method={RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	public void findLevel(HttpServletRequest req , HttpServletResponse resp){
		try {
			List<Select> levels = agencyLevelService.selectListBySelect(
					getCurrentFactoryUser().getFacId(), "'aaa'");
			doResult(resp, true, StatusCode.FINDSUCCESS, levels, ResultType.FIND_SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
			doResult(resp, false, StatusCode.FINDERROR, null, e.getMessage());
		}
	}
	
	/**
	 * @Description: 通过ID查找新闻信息 
	 * @param req
	 * @param resp
	 * @param id  新闻ID
	 * @return void
	 * @author liushengchao
	 * @date 2017年6月14日下午2:57:45
	 * @throws 
	 */
	@RequestMapping(value="/find",method={RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	public void find(HttpServletRequest req , HttpServletResponse resp , @Param("id")Long id){
		try {
			if (LongUtils.isEmpty(id)) {
				doResult(resp, false, StatusCode.FINDERROR, null, ResultType.INPUT_NULL);
				return ;
			}
			FactoryNewsVo entity = factoryNewsService.find(id, 
					getCurrentFactoryUser().getFacId());
			
			//还原特殊字段结构
			if (StringUtils.isNotEmpty(entity.getReciverAge())) {
				entity.setReciverAge(split(entity.getReciverAge()));
			}
			if (StringUtils.isNotEmpty(entity.getReciverArea())) {
				entity.setReciverArea(split(entity.getReciverArea()));
			}
			if (StringUtils.isNotEmpty(entity.getReciverLevel())) {
				entity.setReciverLevel(split(entity.getReciverLevel()));
			}
			
			if (StringUtils.isNotEmpty(entity.getReciverArea()))
				entity.setAreaList(agencyAreaService.findListByNews(entity.getFacId(), 
						"'"+entity.getReciverArea()+"'"));
			else 
				entity.setAreaList(agencyAreaService.findListByNews(entity.getFacId(), "'aaa'"));
		
			doResult(resp, true, StatusCode.FINDSUCCESS, entity, ResultType.FIND_SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
			doResult(resp, false, StatusCode.FINDERROR, null, e.getMessage());
		}
	}
	
	/**
	 * @Description: 分页条件查询新闻信息 
	 * @param req
	 * @param resp
	 * @param title 查询条件
	 * @return void
	 * @author dingjiang
	 * @date 2017年6月14日下午3:04:07
	 * @throws
	 */
	@RequestMapping(value="/selectpage",method={RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	public void selectPage(HttpServletResponse resp, Integer page, Integer rows, 
			String sort, String order, FactoryNewsVo entity){
		try {
			if (page == null) page = 1;
			if (rows == null) rows = 10;

			PageUtils<FactoryNewsEntity> pageinfo = new PageUtils<FactoryNewsEntity>(page, rows, sort, order);
			Map<String, Object> condition = pageinfo.getCondition();
			
			condition.put("facId", getCurrentFactoryUser().getFacId());
			condition.put("type", entity.getType());
			condition.put("reciverType", entity.getReciverType());
			condition.put("beginTime", entity.getBeginTime());
			condition.put("endTime", entity.getEndTime());
			condition.put("newsTitle", entity.getNewsTitle());
			
			factoryNewsService.selectforPage(pageinfo);
			doResult(resp, true, StatusCode.FINDSUCCESS, pageinfo, ResultType.FIND_SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
			doResult(resp, false, StatusCode.EXCEPTIONERROR, null, e.getMessage());
		}
	}
	
	/**
	 * @Description: 修改新闻信息 
	 * @param req
	 * @param resp
	 * @param factoryNews 
	 * @return void
	 * @author liushengchao
	 * @date 2017年6月14日下午3:17:37
	 * @throws 
	 */
	@RequestMapping(value="/modify",method={RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	public void update(HttpServletRequest req, HttpServletResponse resp, FactoryNewsEntity factoryNews){
		try {
			if ( factoryNewsService.find(factoryNews.getId(),getCurrentFactoryUser().getFacId()) == null ) {
				doResult(resp, false, StatusCode.SAVEERROR, null, ResultType.INPUT_ERROR);
				return ;
			}
			
			factoryNews.setCreator(getCurrentFactoryUser().getId());
			factoryNewsService.updateByPrimaryKeySelective(factoryNews);
			doResult(resp, true, StatusCode.SAVESUCCESS, null, ResultType.SAVE_SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
			doResult(resp, false, StatusCode.SAVEERROR, null, e.getMessage());
		}
	}
	
	/**
	 * @Description: 删除新闻信息 
	 * @param req
	 * @param resp
	 * @param id 
	 * @return void
	 * @author liushengchao
	 * @date 2017年6月14日下午3:21:25
	 * @throws 
	 */
	@RequestMapping(value="/delete",method={RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	public void delete(HttpServletRequest req , HttpServletResponse resp , String ids){
		try {
			String[] strs = ids.split(",");
			
			Long[] arrays = new Long[strs.length];
			for(int i = 0; i < strs.length; i++){
				arrays[i] = Long.parseLong(strs[i]);
		    }

			factoryNewsService.deletes(getCurrentFactoryUser().getFacId(), arrays);
			doResult(resp, true, StatusCode.REMOVESUCCESS, null, ResultType.REMOVE_SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
			doResult(resp, false, StatusCode.REMOVEERROR, null, e.getMessage());
		}
	}
	
	
	private String split(String text) {
		if (",".equals(text.substring(text.length()-1)))
			text = text.substring(0, text.length()-1);
		return text.replaceAll("[ ]+", "");
	}
}
